/*
 * @Author: 聆风
 * @Date: 2025-08-23 18:12:00
 * @LastEditors: 聆风 522361856@qq.com
 * @LastEditTime: 2025-08-24 01:26:21
 * @FilePath: \​monoFE​​\scripts\build.js
 *
 * Copyright (c) 2025 by 聆风, All Rights Reserved.
 */
import { rollup } from "rollup";
import { getPackages, cleanDist } from "./utils.js";
import { getAllConfigs } from "./rollup.config.mjs";

// 清理并构建单个包
async function buildPackage(pkg) {
  try {
    // console.log(`🧹 Cleaning dist for ${pkg}...`);
    // await cleanDist(pkg);

    console.log(`📦 Building ${pkg}...`);
    const configs = getAllConfigs().filter((config) =>
      config.input.includes(`${pkg}`)
    );

    // 并行构建所有配置
    await Promise.all(
      configs.map(async (config) => {
        const bundle = await rollup(config);

        // 处理多输出配置
        if (Array.isArray(config.output)) {
          await Promise.all(
            config.output.map((output) => bundle.write(output))
          );
        } else {
          await bundle.write(config.output);
        }

        await bundle.close();
      })
    );

    console.log(`✅ ${pkg} built successfully!`);
  } catch (error) {
    console.error(`❌ Error building ${pkg}:`, error);
    throw error;
  }
}

// 构建所有包
async function buildAll() {
  const packages = getPackages();
  const startTime = Date.now();
  console.log("🚀 Starting build process...");
  console.log(`🔍 Found ${packages.length} packages to build`);

  try {
    // 串行构建避免资源竞争
    for (const pkg of packages) {
      await cleanDist(pkg);
      await buildPackage(pkg);
    }

    const duration = ((Date.now() - startTime) / 1000).toFixed(2);
    console.log(`🎉 All packages built successfully in ${duration}s!`);
  } catch (error) {
    console.error("🚨 Critical build error:", error);
    process.exit(1);
  }
}

// 执行构建
buildAll();
